import { ipcMain } from 'electron'
import { requests } from '../api/http'
import { logger } from '@/settings';
import { auth } from '@/store';

/**
 * 用户注册监听器
 * @param event 
 * @param email 
 * @param password 
 */
async function UserRegistListener(event: Electron.IpcMainEvent, email: string, password: string) {
  try {
    const response = await requests.registerUser(email, password);
    event.reply('user-regist-reply', response.data);
  } catch (error) {
    logger.warn(error)
  }
}

/**
 * # 用户激活监听器
 * 当用户注册完成后，需要接受邮件激活才能够登陆使用
 * @param event 
 * @param email 
 * @param password 
 * @param emailAuthCode 
 */
async function UseActiveListener(event: Electron.IpcMainEvent, email: string, password: string, emailAuthCode: string) {
  try {
    const response = await requests.activeUserAccount(email, password, emailAuthCode);
    event.reply('user-active-reply', response.data);
  } catch (error) {
    logger.warn(error)
  }
}


/**
 * 用户登陆监听器
 * - 先请求API，再通过通道 'user-login-reply' 将请求结果返回给渲染进程
 * @param event 
 * @param email 
 * @param password 
 */
async function UserLoginListener(event: Electron.IpcMainEvent, email: string, password: string) {
  try {
    const response = await requests.loginUser(email, password);
    event.reply('user-login-reply', response.data);
  } catch (error) {
    logger.warn(error)
  }
}

/**
 * 获取二维码键监听器
 * @param event 
 */
async function GetQrcodeKeyListener(event: Electron.IpcMainEvent) {
  try {
    const key = await requests.getQrcodeKey();
    event.reply('get-qrcode-key-reply', key);
  } catch (error) {
    logger.warn(error)
  }
}

/**渲染进程通过主进程发起Http请求的通信 */
export function HTTPRequesrsIPC() {
  ipcMain.on('user-regist', UserRegistListener);        // 用户注册通信
  ipcMain.on('user-active', UseActiveListener);         // 用户激活通信
  ipcMain.on('user-login', UserLoginListener);          // 用户登陆通信
  ipcMain.on('get-qrcode-key', GetQrcodeKeyListener);   // 获取二维码键
}
